#!/usr/bin/env bash

source ../../lib/shell/env.sh
source ./cpu_stress.sh

function clean() {
    echo "clean $CPU_LOAD_LOG"
    test -f "$CPU_LOAD_LOG" && rm -rf "$CPU_LOAD_LOG" ||:
    echo "clean $CPU_LOAD_RESULTS_LOG"
    test -f "$CPU_LOAD_RESULTS_LOG" && rm -rf "$CPU_LOAD_RESULTS_LOG" ||:
    if pgrep stress-ng >/dev/null 2>&1;then
        echo "kill -9 \`pgrep stress-ng\`"
        kill -9 `pgrep stress-ng`
    else
        echo "Nothing to kill for cpu Computational power test."
    fi
}

function cpu_calc_power_test() {
    local cpu_used_nums

    #online cpu info, reserve two cpu
    echo -e "Get online cpu: \n=============================="
    for on_cpu in $CPU_ONLINE_NAME;do echo "${CPU_PATH}/$on_cpu";done
    echo -e "=============================="
    if test $CPU_ONLINE_NUMS -gt 0 && test $CPU_ONLINE_NUMS -lt 3;then
        cpu_used_nums=1
    elif test $CPU_ONLINE_NUMS -ge 3;then
        cpu_used_nums=$(echo "$CPU_ONLINE_NUMS - 2"|bc)
    else
        echo "warning: No cpu is online." && test_skip
    fi
    cpuload_monitor_on_usr $cpu_used_nums &

    check_cmd "stress-ng"
    run_cmd "stress-ng --cpu $cpu_used_nums --cpu-method all --verify --timeout=$RUNTIME"
    wait

    echo "Check cpu load log"
    if test ! -f $CPU_LOAD_RESULTS_LOG;then
        echo "Error: no such file $CPU_LOAD_RESULTS_LOG" && test_fail
    else
        if grep -wq "Error" $CPU_LOAD_RESULTS_LOG;then
            awk '{print $0}' < $CPU_LOAD_RESULTS_LOG && test_fail
        fi
        awk '{print $0}' < $CPU_LOAD_RESULTS_LOG
    fi
}

trap "clean" EXIT

# # # # # # # # # # # # # # main # # # # # # # # # # # #
stress_cpu_env
get_online_cpu || test_fail

cpu_calc_power_test && test_pass || test_fail
